### =========================================================================
### Preparation
### =========================================================================

### Please load the function for combining polygon and SDM maps
source("./functions/combine_range_sdm.R")

### (Optional) Please set the names for output maps for each species, and the length should be the same with input occurrence .csv files
### If this is not set, the names would be the same with the input maps.
species <- NA

### Please set the resolution for your final maps.
### The default resolution is 0.2 degree.
map_res <- 0.2

### Set input and output paths
path.polygon <- "3.1_mapping_Polygons/raster_range" # folder with input polygon maps
path.sdm <- "3.2_mapping_SDM/ComitteeVote" # folder with input SDM maps
output.plot <- "3.3_mapping_Combined/Combine_maps" # folder to save output combine maps
output.raster <- "3.3_mapping_Combined/Combine_raster" # folder to save output combine map rasters


### =========================================================================
### Please run following codes to get the final maps in the folder "Combined" under your working directory
### =========================================================================

#install packages globally

# set a local mirror server
options(repos=structure(c(CRAN="https://stat.ethz.ch/CRAN/")))

# Packages to load
packages <- list("maps", "raster")

# Install missing ones and load all packages
for (p in packages) {
  if(!library(package = p, logical.return = TRUE, character.only = TRUE)){
    install.packages(p)
    library(package = p, character.only = TRUE)
  } else {   
    library(package = p, character.only = TRUE) 
  }
}

if(!file.exists(output.raster)) {dir.create(output.raster, recursive = T)}
if(!file.exists(output.plot)) {dir.create(output.plot, recursive = T)}

spsdm.all <- sort(list.files(path.sdm))
species.sdm <- sort(gsub("[/.]tif", "", spsdm.all))
species.polygon <- sort(sapply(species.sdm, function(x){list.files(path.polygon, pattern = x)}))

if (!all(spsdm.all == species.polygon)) {
  print("WARNING: Please check if the input polygon and SDM maps are matched.")
}

if (is.na(species)){species <- species.sdm}

summaryall <- data.frame()
for (i in 1:length(spsdm.all)){
  
  print(paste("START WITH",i,"/",length(spsdm.all),":",as.character(splist[i])))
   
  if (file.exists(file.path(path.sdm, spsdm.all[i]))){
  
  sppolygons <- raster(file.path(path.polygon, species.polygon[i]))
  species_sdm <- raster(file.path(path.sdm, spsdm.all[i]))

    combinemap <- combine.range.sdm.fun(species_name=species, rast_sdm=species_sdm, rast_range=sppolygons, 
                          write_plot=T, dest_plot= output.plot,
                          final_resolution=map_res, dest_raster= output.raster, overwrite=T)
    } else {print(paste(spsdm, "SDM map does not exist."))}
    
  print(paste0("COMPLETED: [ ",round(i/length(spsdm.all),2)*100, "% ]"))
  
  tmp <- tempfile()
  do.call(file.remove, list(list.files("tmp", full.names = TRUE)))
  rm(sppolygons, species_sdm, combinemap)
  }
